package com.spic.business.train.plan.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spic.business.common.core.utils.poi.BusinessExcelUtil;
import com.spic.business.train.plan.domain.TrainPlan;
import com.spic.business.train.plan.domain.YearPlanExcel;
import com.spic.business.train.plan.domain.YearPlanReadListener;
import com.spic.business.train.plan.service.ITrainPlanService;
import com.spic.business.train.plan.service.YearPlanService;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.utils.poi.ExcelUtil;
import com.spic.common.core.web.controller.BaseController;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.common.core.web.page.TableDataInfo;
import com.spic.common.datascope.annotation.DataScope;
import com.spic.common.log.annotation.Log;
import com.spic.common.log.enums.BusinessType;
import com.spic.common.security.annotation.PreAuthorize;
import com.spic.system.api.RemoteDeptService;
import com.spic.system.api.RemoteFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 培训计划Controller
 *
 * @author spic
 * @date 2021-10-15
 */
@Api(tags = "培训方案", description  = "培训方案")
@RestController
@RequestMapping("/train/plan")
public class TrainPlanController extends BaseController {
    @Autowired
    private ITrainPlanService trainPlanService;

    @Autowired
    RemoteFileService fileService;

    @Autowired
    private YearPlanService yearPlanService;
    @Autowired
    private RemoteDeptService remoteDeptService;


    /**
     * 查询培训计划列表
     */
    @DataScope(deptAlias = "d")
    @PreAuthorize(hasPermi = "business/train:plan:list")
    @GetMapping("/list")
    @ApiOperation(value = "查询列表信息")
    public TableDataInfo list(TrainPlan trainPlan) {
        //获取部门及子部门
        if ( null !=  trainPlan.getDeptId()){
            List<Long> deptIds = remoteDeptService.getDeptAndChildren(trainPlan.getDeptId()).getData();
            trainPlan.setDeptIds(deptIds);
        }
        startPage();
        List<TrainPlan> list = trainPlanService.selectTrainPlanList(trainPlan);
        return getDataTable(list);
    }

    /**
     * 导出培训计划列表
     */
    @DataScope(deptAlias = "d")
    @PreAuthorize(hasPermi = "business/train:plan:export")
    @Log(title = "培训计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TrainPlan trainPlan) throws IOException {
        List<TrainPlan> list = trainPlanService.selectTrainPlanList(trainPlan);
        ExcelUtil<TrainPlan> util = new BusinessExcelUtil<>(TrainPlan.class);
        util.exportExcel(response, list, "培训计划数据");
    }

    @GetMapping("template")
    public void  downloadTemplate()
    {
        EasyExcel.write("template-year-plan.xlsx", TrainPlan.class).sheet().doWrite(new ArrayList<TrainPlan>());

    }

    @PostMapping("add")
    public AjaxResult add(@RequestBody YearPlanExcel yearPlanExcel)
    {
        return AjaxResult.success(yearPlanService.save(yearPlanExcel));
    }

    @PostMapping("update")
    public AjaxResult update(@RequestBody YearPlanExcel yearPlanExcel)
    {
        return AjaxResult.success(yearPlanService.updateById(yearPlanExcel));
    }

    @PostMapping("delete/{id}")
    public AjaxResult deleteById(@PathVariable("id") String id)
    {
        return AjaxResult.success(yearPlanService.removeById(id));
    }

    @GetMapping("item/{id}")
    public AjaxResult getItemById(@PathVariable("id") String id)
    {
        return AjaxResult.success(yearPlanService.getById(id));
    }


    @PostMapping("importPlan")
    public AjaxResult importData(MultipartFile file, boolean updateSupport)
    {

        AjaxResult ajaxResult = AjaxResult.success();
        InputStream inputStream = null;
        try
        {
            inputStream = file.getInputStream();
        }
        catch (IOException e)
        {
            logger.error("import file,read stream error.");
        }
        EasyExcel.read(inputStream, YearPlanExcel.class, new YearPlanReadListener(ajaxResult, yearPlanService)).autoTrim(true).extraRead(CellExtraTypeEnum.MERGE).headRowNumber(4).sheet().doRead();
        return ajaxResult;
    }

    @GetMapping("page")
    public TableDataInfo page(YearPlanExcel yearPlanExcel)
    {
        startPage();
        List<YearPlanExcel> list = yearPlanService.list(new QueryWrapper<YearPlanExcel>(yearPlanExcel));
        return getDataTable(list);
    }

    /**
     * 获取培训计划详细信息
     */
    @PreAuthorize(hasPermi = "business/train:plan:query")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取培训计划详细信息")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(trainPlanService.selectTrainPlanById(id));
    }

    /**
     * 新增培训计划
     */
    @PreAuthorize(hasPermi = "business/train:plan:add")
    @Log(title = "培训计划", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "")
    public AjaxResult add(@Validated @RequestBody TrainPlan trainPlan) {
        trainPlan.checkParam();
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            trainPlan.setId(uuid);
            return toAjax(trainPlanService.insertTrainPlan(trainPlan));
        } catch (Exception e) {
            Throwable cause = e.getCause();
            if (cause instanceof java.sql.SQLIntegrityConstraintViolationException) {
                //错误信息
                String errMsg =  cause.getMessage();
                //根据约束名称定位是那个字段
                if (StringUtils.isNotBlank(errMsg) && errMsg.indexOf("planName") != -1) {
                    return AjaxResult.error("项目名已存在");
                } else {
                    return AjaxResult.error("新增失败！");
                }
            } else {
                return AjaxResult.error("新增失败！");
            }
        }
    }


    /**
     * 修改培训计划
     */
    @PreAuthorize(hasPermi = "business/train:plan:edit")
    @Log(title = "培训计划", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改培训计划")
    public AjaxResult edit(@RequestBody TrainPlan trainPlan) {
        return toAjax(trainPlanService.updateTrainPlan(trainPlan));
    }

    /**
     * 删除培训计划
     */
    @PreAuthorize(hasPermi = "business/train:plan:remove")
    @Log(title = "培训计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除培训计划")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(trainPlanService.deleteTrainPlanByIds(ids));
    }


}
